package com.coldworks.coldjoke.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.coldworks.base.BaseThread;
import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.base.util.BaseCONST;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.model.ReplyModel;
import com.coldworks.coldjoke.util.CONST;
import com.coldworks.coldjoke.util.NetworkUtil;

public class FetchRepliesTask2 extends BaseThread {
	private Context context;
	private String url;
	private List<ReplyModel> list;
	private Handler handler;

	public FetchRepliesTask2(Context context, Handler handler, String id) {
		this.context = context;
		this.handler = handler;
		this.list = new ArrayList<ReplyModel>();
		this.url = CONST.URL.COMENT + "?action=getOneJokeComments&joke_id="
				+ id + "&page_num=1&data_type=json";
	}

	@Override
	public void run() {
		Message message;
		DefaultHttpClient httpclient;
		HttpGet get = new HttpGet(url);
		httpclient = BaseNetworkManager.getInstance().createHttpClient(context);
		JSONArray jsonArray = null;
		ReplyModel jokeReplyInfo = null;
		try {
			String sessionId = UserManager.getInstance().getSessionId();
			get.setHeader("COOKIE", "webpy_session_id=" + sessionId);
			HttpResponse response = httpclient.execute(get);
			if (isInterrupted()) {
				log.info("cancelled");
				message = handler.obtainMessage(BaseCONST.OP.CANCEL);
				handler.sendMessage(message);
				return;
			}
			if (response.getStatusLine().getStatusCode() == 200) {
				Header contentEncoding = response
						.getFirstHeader("Content-Encoding");
				JSONObject jsonObject = null;
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					jsonObject = NetworkUtil.getInstance().getJsonObjectByGzip(
							response.getEntity().getContent());
				} else {
					jsonObject = NetworkUtil.getInstance().getJSONObject(
							response.getEntity().getContent());
				}
				if (jsonObject == null) {
					message = handler.obtainMessage(BaseCONST.OP.FAIL);
					handler.sendMessage(message);
					return;
				}
				if (isInterrupted()) {
					log.info("cancelled");
					message = handler.obtainMessage(BaseCONST.OP.CANCEL);
					handler.sendMessage(message);
					return;
				}
				jsonArray = jsonObject.getJSONArray("comments");
				JSONObject json;
				for (int i = 0; i < jsonArray.length(); i++) {
					jokeReplyInfo = new ReplyModel();
					json = jsonArray.getJSONObject(i);
					JSONObject author = new JSONObject(json.getString("author"));
					jokeReplyInfo.setUserName(author.getString("username"));
					jokeReplyInfo.setUserId(json.getString("Userid"));
					jokeReplyInfo.setReplyContent(json.getString("content"));
					list.add(jokeReplyInfo);
				}
				message = handler.obtainMessage(BaseCONST.OP.SUCC, list);
				handler.sendMessage(message);
				log.info("success");
				return;
			} else {
				log.info(String.valueOf(response.getStatusLine()
						.getStatusCode()));
				message = handler.obtainMessage(BaseCONST.OP.FAIL);
				handler.sendMessage(message);
				return;
			}
		} catch (ClientProtocolException e) {
			log.error("", e);
			message = handler.obtainMessage(BaseCONST.OP.FAIL);
			handler.sendMessage(message);
			return;
		} catch (IOException e) {
			log.error("", e);
			message = handler.obtainMessage(BaseCONST.OP.FAIL);
			handler.sendMessage(message);
			return;
		} catch (JSONException e) {
			log.error("", e);
			message = handler.obtainMessage(BaseCONST.OP.FAIL);
			handler.sendMessage(message);
			return;
		} finally {

		}
	}

}